package net.vsame.url2sql.render;

import java.io.IOException;
import java.io.PrintWriter;

import net.vsame.url2sql.helper.Url2SqlContext;
import net.vsame.url2sql.helper.WebHelper;

public class JsonpRender extends Render{

	private static final long serialVersionUID = 4936638023448708103L;
	private boolean enabledJsonp = true;

	@Override
	public void render() {
		Url2SqlContext c = WebHelper.getContext();
		response.setContentType("application/x-javascript; charset="+encoding);
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.write(getJosnp(c));
			out.flush();
		} catch (IOException e) {
		} finally {
			if(out != null){
				out.close();
			}
		}
	}
	
	private String getJosnp(Url2SqlContext context) {
		String method = context.getRequest().getParameter("callback");
		method = method == null ? "callback" : method;
		String retVal = null;
		if(enabledJsonp){
			retVal = ";" + method + "(" + JsonRender.getJosn(context) + ");";
		}else{
			retVal = ";" + method + "(" + "{'code':'-7', 'msg':'disabled jsonp'}" + ");";
		}
		return retVal;
	}
	public boolean isEnabledJsonp() {
		return enabledJsonp;
	}
	public void setEnabledJsonp(boolean enabledJsonp) {
		this.enabledJsonp = enabledJsonp;
	}

}
